<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      label-width="100px"
    >
      <el-form-item label="文本内容" prop="qrcodeText">
        <el-input
          v-model="queryParams.qrcodeText"
          placeholder="请输入二维码文本内容"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="顶部文字" prop="topFont">
        <el-input
          v-model="queryParams.topFont"
          placeholder="请输入二维码顶部文字"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="中心文字" prop="centerFont">
        <el-input
          v-model="queryParams.centerFont"
          placeholder="请输入二维码中心文字"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="底部文字" prop="bottomFont">
        <el-input
          v-model="queryParams.bottomFont"
          placeholder="请输入二维码底部文字"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          :disabled="multiple"
          type="primary"
          icon="el-icon-refresh"
          size="mini"
          @click="handleUpdateQrCode"
          >重新生成
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          :disabled="multiple"
          type="success"
          icon="el-icon-printer"
          size="mini"
          @click="handlePrint"
          >打印</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          :disabled="multiple"
          type="primary"
          icon="el-icon-download"
          size="mini"
          @click="handleBatchDownload"
          >批量下载</el-button
        >
      </el-col>
      <el-col :span="1.5" style="float: right" v-if="dynamicColumnSetting">
        <el-popover
          placement="bottom"
          min-width="80"
          trigger="click"
          popper-class="col-setting-popover"
        >
          <el-button
            slot="reference"
            type="primary"
            icon="el-icon-setting"
            size="mini"
            >筛选</el-button
          >
          <div class="col-setting-title">显示设置</div>
          <el-checkbox-group
            v-model="visibleIndexs"
            :min="0"
            class="col-setting-group"
          >
            <el-checkbox
              v-for="colInfo in columnInfos"
              :label="colInfo.index"
              :key="colInfo.index"
              :disabled="colInfo.disabled"
              v-show="!colInfo.disabled || showAlwaysShowColumnInCheckbox"
              >{{ colInfo.label }}</el-checkbox
            >
          </el-checkbox-group>
        </el-popover>
      </el-col>
    </el-row>

    <el-table
      ref="pageTable"
      class="loading-area"
      :data="dataList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="ID"
        align="center"
        prop="id"
        v-if="columnVisibles[0]"
      />
      <el-table-column
        label="二维码文本内容"
        align="center"
        prop="qrcodeText"
        v-if="columnVisibles[1]"
      />
      <el-table-column
        label="二维码顶部文字"
        align="center"
        prop="topFont"
        v-if="columnVisibles[2]"
      />
      <el-table-column
        label="二维码中心文字"
        align="center"
        prop="centerFont"
        v-if="columnVisibles[3]"
      />
      <el-table-column
        label="二维码底部文字"
        align="center"
        prop="bottomFont"
        v-if="columnVisibles[4]"
      />
      <el-table-column
        label="二维码图片"
        align="center"
        prop="qrcodeUrl"
        v-if="columnVisibles[5]"
      >
        <template slot-scope="props">
          <el-form label-position="left">
            <el-image
              :src="props.row.qrcodeUrl"
              :preview-src-list="[props.row.qrcodeUrl]"
            >
            </el-image>
          </el-form>
        </template>
      </el-table-column>

      <el-table-column
        label="生成时间"
        align="center"
        prop="createTime"
        v-if="columnVisibles[6]"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleDownload(scope.row)"
            >下载二维码
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="文本内容" prop="qrcodeText">
              <el-input
                v-model="form.qrcodeText"
                placeholder="请输入二维码文本内容"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="顶部文字" prop="topFont">
              <el-input
                v-model="form.topFont"
                placeholder="请输入二维码顶部文字"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="中心文字" prop="centerFont">
              <el-input
                v-model="form.centerFont"
                placeholder="请输入二维码中心文字"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="底部文字" prop="bottomFont">
              <el-input
                v-model="form.bottomFont"
                placeholder="请输入二维码底部文字"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">生成</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 打印二维码对话框 -->
    <el-dialog
      title="打印二维码"
      :visible.sync="printDialogOpen"
      width="1000px"
    >
      <div id="printMe">
        <el-form>
          <template v-for="(item, index) in qrCodeImageList">
            <div @mouseenter="enter(index)" @mouseleave="leave()" :key="index">
              <el-image
                style="width: 200px;margin-right: 30px;"
                :key="index"
                :src="item"
              >
              </el-image>
              <i
                v-show="seen && index == current"
                class="el-icon-delete"
                @click="deletePrint(index)"
              ></i>
            </div>
          </template>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" v-print="'#printMe'" @click="closePrintDialog"
          >确 定</el-button
        >
        <el-button @click="closePrintDialog">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped>
@page {
  size: auto A4 landscape;
  margin: 3mm;
}

#printMe .el-icon-delete {
  position: absolute;
  z-index: 99999999;
  margin-left: -60px;
  margin-top: 5px;
}
</style>

<script>
import {
  list,
  get,
  add,
  update,
  remove,
  createQrcode
} from "@/api/comm/qrcodeInfo";
import { download } from "@/utils/commonUtil";
export default {
  name: "qrcodeInfo",
  data() {
    return {
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 表格数据
      dataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      printDialogOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: undefined,
        qrcodeText: undefined,
        topFont: undefined,
        centerFont: undefined,
        bottomFont: undefined
      },
      columnInfos: [], // 所有列信息
      showAlwaysShowColumnInCheckbox: true,
      dynamicColumnSetting: true,
      columnVisibles: new Array(7).fill(true), //设置列可见性
      visibleIndexs: [], // 可见列的下标集合
      alwaysShowColumnIndexs: [1, 5], //总是显示的列的下标（不可隐藏的列）,列下标从 0 开始
      hidenColumnIndexs: [], //隐藏列的下标集合
      qrCodeImageList: [], //打印的二维码图片集合
      seen: false,
      current: 0,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        qrcodeText: [
          { required: true, message: "二维码文本内容不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询列表 */
    getList() {
      list(this.queryParams).then(response => {
        this.dataList = response.data.rows;
        this.total = response.data.total;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    closePrintDialog() {
      this.printDialogOpen = false;
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        qrcodeText: undefined,
        topFont: undefined,
        centerFont: undefined,
        bottomFont: undefined,
        tenantId: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "二维码生成";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      get(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "二维码生成";
      });
    },
    /** 打印按钮操作 */
    handlePrint(row) {
      this.qrCodeImageList = [];
      const selection = this.$refs.pageTable.selection;
      this.qrCodeImageList = selection.map(item => item.qrcodeUrl);
      this.printDialogOpen = true;
    },
    /** 更新二维码按钮操作 */
    handleUpdateQrCode(row) {
      const id = row.id || this.ids;
      createQrcode(id).then(response => {
        this.getList();
      });
    },
    /** 下载按钮操作 */
    handleDownload(row) {
      const fileUrl = row.qrcodeUrl;
      const fileName = fileUrl.substr(fileUrl.lastIndexOf("/") + 1);
      console.log(fileName);
      download(fileUrl, fileName);
    },
    // 批量下载按钮
    handleBatchDownload(row) {
      const id = row.id || this.ids;
      const baseURL = process.env.VUE_APP_BASE_API;
      window.location.href = baseURL + "/api/comm/qrcodeInfo/zipDownload/" + id;
    },
    // 删除打印图片
    deletePrint(index) {
      if (this.qrCodeImageList.length > 1) {
        this.qrCodeImageList.splice(index, 1);
      } else {
        this.msgError("至少要有一张需要打印二维码");
      }
    },
    enter(index) {
      this.seen = true;
      this.current = index;
    },
    leave() {
      this.seen = false;
      this.current = null;
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id !== undefined) {
            update(this.form).then(response => {
              if (response.code === 0) {
                this.msgSuccess("生成成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            add(this.form).then(response => {
              if (response.code === 0) {
                this.msgSuccess("生成成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除ID为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return remove(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function() {});
    },

    oprColumns(indexs, isShow) {
      let self = this;
      indexs.forEach(index => {
        self.$set(self.columnVisibles, index, isShow);
      });
    }
  },
  mounted() {
    let self = this;
    if (self.$refs.pageTable.$slots.default) {
      let columnIndex = 0;
      self.$refs.pageTable.$slots.default.forEach((columnIns, index) => {
        if (columnIns.componentOptions === undefined) {
          return;
        }
        let props = columnIns.componentOptions.propsData;
        if (
          props.prop === undefined ||
          props.type === "selection" ||
          props.type === "index"
        ) {
          return;
        }
        // 保存所有列的信息
        let label = props.label;
        let colName = props.prop;
        self.columnInfos.push({
          label: label,
          colName: colName,
          index: columnIndex,
          disabled: false
        });
        // 记录初始展示的列的下标
        if (self.hidenColumnIndexs.indexOf(columnIndex) === -1) {
          self.visibleIndexs.push(columnIndex);
        }
        columnIndex++;
      });
      // 处理总是显示的列（不可隐藏的列）
      self.alwaysShowColumnIndexs.forEach(
        index => (self.columnInfos[index].disabled = true)
      );
      // 处理初始隐藏的列
      self.oprColumns(self.hidenColumnIndexs, false);
    }
  },
  beforeUpdate() {
    let self = this;
    self.$nextTick(_ => {
      self.$refs.pageTable.doLayout();
    });
  },
  watch: {
    visibleIndexs(newValue, oldValue) {
      let self = this;
      let willHideIndexs = [],
        willShowIndexs = [];
      willShowIndexs = newValue.filter(index => {
        return oldValue.indexOf(index) === -1;
      });
      willHideIndexs = oldValue.filter(index => {
        return newValue.indexOf(index) === -1;
      });
      self.oprColumns(willShowIndexs, true);
      self.oprColumns(willHideIndexs, false);
    }
  }
};
</script>
